package com.work.yshop.provider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 商品内容提供者，用于管理商品数据
 */
public class ProductProvider extends ContentProvider {
    private static final String TAG = "ProductProvider";

    private static final String AUTHORITY = "com.work.yshop.provider";
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/products");
    
    private static final int PRODUCTS = 1;
    private static final int PRODUCT_ID = 2;
    
    private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    
    static {
        uriMatcher.addURI(AUTHORITY, "products", PRODUCTS);
        uriMatcher.addURI(AUTHORITY, "products/#", PRODUCT_ID);
    }
    
    private DatabaseHelper dbHelper;
    
    @Override
    public boolean onCreate() {
        dbHelper = new DatabaseHelper(getContext());
        // 检查并插入示例数据
        checkAndInsertSampleData();
        return true;
    }
    
    /**
     * 检查数据库是否为空，如果为空则插入示例数据
     */
    private void checkAndInsertSampleData() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query("products", new String[]{"COUNT(*)"}, null, null, null, null, null);
        
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    int count = cursor.getInt(0);
                    if (count == 0) {
                        Log.d(TAG, "数据库为空，插入示例数据");
                        insertSampleProducts(db);
                    } else {
                        Log.d(TAG, "数据库已有数据: " + count + " 条");
                    }
                }
            } finally {
                cursor.close();
            }
        }
    }
    
    /**
     * 插入示例商品数据
     */
    private void insertSampleProducts(SQLiteDatabase db) {
        // 创建示例商品数据
        ContentValues values1 = new ContentValues();
        values1.put("name", "新鲜有机蔬菜 无农药绿色食品");
        values1.put("description", "来自高山的有机蔬菜，无农药，绿色健康");
        values1.put("price", 10.0);
        values1.put("original_price", 12.0);
        values1.put("unit", "斤");
        values1.put("stock", 100);
        values1.put("sales_count", 344);
        values1.put("category", "粮油");
        values1.put("image_url", "https://images.pexels.com/photos/2286776/pexels-photo-2286776.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1");
        values1.put("status", 1);
        values1.put("seller_id", 1);
        db.insert("products", null, values1);
        
        ContentValues values2 = new ContentValues();
        values2.put("name", "南阳优质面粉 东北特产");
        values2.put("description", "东北特产面粉，口感细腻，营养丰富");
        values2.put("price", 25.0);
        values2.put("original_price", 30.0);
        values2.put("unit", "袋");
        values2.put("stock", 50);
        values2.put("sales_count", 334);
        values2.put("category", "粮油");
        values2.put("image_url", "https://images.pexels.com/photos/162825/flour-wheat-flour-wheat-food-162825.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1");
        values2.put("status", 1);
        values2.put("seller_id", 1);
        db.insert("products", null, values2);
        
        ContentValues values3 = new ContentValues();
        values3.put("name", "东北花生米 红衣花生仁");
        values3.put("description", "东北特产花生，颗粒饱满，香脆可口");
        values3.put("price", 4.5);
        values3.put("original_price", 5.5);
        values3.put("unit", "斤");
        values3.put("stock", 200);
        values3.put("sales_count", 106);
        values3.put("category", "特产");
        values3.put("image_url", "https://images.pexels.com/photos/4110251/pexels-photo-4110251.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1");
        values3.put("status", 1);
        values3.put("seller_id", 1);
        db.insert("products", null, values3);
        
        ContentValues values4 = new ContentValues();
        values4.put("name", "金秋梨香 金秋梨蜜");
        values4.put("description", "金秋梨香，果肉细腻，汁水丰富");
        values4.put("price", 12.0);
        values4.put("original_price", 15.0);
        values4.put("unit", "斤");
        values4.put("stock", 80);
        values4.put("sales_count", 493);
        values4.put("category", "水果");
        values4.put("image_url", "https://images.pexels.com/photos/1132047/pexels-photo-1132047.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1");
        values4.put("status", 1);
        values4.put("seller_id", 1);
        db.insert("products", null, values4);
        
        ContentValues values5 = new ContentValues();
        values5.put("name", "四川红心猕猴桃 奇异果");
        values5.put("description", "四川特产红心猕猴桃，果肉细腻，营养丰富");
        values5.put("price", 6.8);
        values5.put("original_price", 8.0);
        values5.put("unit", "个");
        values5.put("stock", 150);
        values5.put("sales_count", 521);
        values5.put("category", "水果");
        values5.put("image_url", "https://images.pexels.com/photos/51312/kiwi-fruit-vitamins-healthy-eating-51312.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1");
        values5.put("status", 1);
        values5.put("seller_id", 1);
        db.insert("products", null, values5);
        
        Log.d(TAG, "已成功插入5条示例商品数据");
    }
    
    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor;
        
        switch (uriMatcher.match(uri)) {
            case PRODUCTS:
                cursor = db.query("products", projection, selection, selectionArgs, null, null, sortOrder);
                break;
            case PRODUCT_ID:
                long id = ContentUris.parseId(uri);
                cursor = db.query("products", projection, "_id = ?", new String[]{String.valueOf(id)}, null, null, sortOrder);
                break;
            default:
                throw new IllegalArgumentException("未知URI: " + uri);
        }
        
        // 设置通知URI
        if (getContext() != null) {
            cursor.setNotificationUri(getContext().getContentResolver(), uri);
        }
        
        return cursor;
    }
    
    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        switch (uriMatcher.match(uri)) {
            case PRODUCTS:
                return "vnd.android.cursor.dir/vnd.com.work.yshop.provider.products";
            case PRODUCT_ID:
                return "vnd.android.cursor.item/vnd.com.work.yshop.provider.products";
            default:
                throw new IllegalArgumentException("未知URI: " + uri);
        }
    }
    
    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        if (uriMatcher.match(uri) != PRODUCTS) {
            throw new IllegalArgumentException("未知URI: " + uri);
        }
        
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long id = db.insert("products", null, values);
        
        if (id > 0) {
            Uri productUri = ContentUris.withAppendedId(CONTENT_URI, id);
            if (getContext() != null) {
                getContext().getContentResolver().notifyChange(productUri, null);
            }
            return productUri;
        }
        
        return null;
    }
    
    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;
        
        switch (uriMatcher.match(uri)) {
            case PRODUCTS:
                count = db.delete("products", selection, selectionArgs);
                break;
            case PRODUCT_ID:
                long id = ContentUris.parseId(uri);
                count = db.delete("products", "_id = ?", new String[]{String.valueOf(id)});
                break;
            default:
                throw new IllegalArgumentException("未知URI: " + uri);
        }
        
        if (count > 0 && getContext() != null) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        
        return count;
    }
    
    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int count;
        
        switch (uriMatcher.match(uri)) {
            case PRODUCTS:
                count = db.update("products", values, selection, selectionArgs);
                break;
            case PRODUCT_ID:
                long id = ContentUris.parseId(uri);
                count = db.update("products", values, "_id = ?", new String[]{String.valueOf(id)});
                break;
            default:
                throw new IllegalArgumentException("未知URI: " + uri);
        }
        
        if (count > 0 && getContext() != null) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        
        return count;
    }
    
    /**
     * 数据库帮助类
     */
    private static class DatabaseHelper extends SQLiteOpenHelper {
        
        private static final String DATABASE_NAME = "yshop.db";
        private static final int DATABASE_VERSION = 2;
        
        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
        
        @Override
        public void onCreate(SQLiteDatabase db) {
            // 创建商品表
            db.execSQL(
                    "CREATE TABLE IF NOT EXISTS products (" +
                    "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
                    "name TEXT NOT NULL," +
                    "price REAL NOT NULL," +
                    "original_price REAL," +
                    "unit TEXT," +
                    "stock INTEGER NOT NULL," +
                    "sales_count INTEGER," +
                    "description TEXT," +
                    "category TEXT," +
                    "image_url TEXT," +
                    "status INTEGER DEFAULT 1," +
                    "shop_id INTEGER," +
                    "user_id INTEGER," +
                    "user_type INTEGER," +
                    "seller_id INTEGER," +
                    "publish_date TEXT," +
                    "update_date TEXT" +
                    ");");
        }
        
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // 如果版本升级，可以在这里处理数据库迁移
            if (oldVersion < 2) {
                // 添加seller_id列
                try {
                    db.execSQL("ALTER TABLE products ADD COLUMN seller_id INTEGER;");
                    Log.d(TAG, "成功添加seller_id列");
                    
                    // 为现有数据设置默认seller_id值
                    ContentValues values = new ContentValues();
                    values.put("seller_id", 1);
                    db.update("products", values, null, null);
                    Log.d(TAG, "已为现有商品设置默认seller_id=1");
                } catch (Exception e) {
                    Log.e(TAG, "添加seller_id列失败: " + e.getMessage(), e);
                }
            }
        }
    }
} 